package io.gitee.devaper.starlight.security

import com.baomidou.mybatisplus.extension.kotlin.*
import io.gitee.devaper.starlight.common.constant.*
import io.gitee.devaper.starlight.common.entity.po.*
import io.gitee.devaper.starlight.common.mapper.*
import io.gitee.devaper.starlight.common.util.*
import io.gitee.devaper.starlight.security.exception.*
import org.springframework.security.core.userdetails.*
import org.springframework.stereotype.Component

@Component
open class DefaultUserDetailService(
    private val userMapper: UserMapper
) : UserDetailsService {

    private val usernamePattern = regex(USERNAME_PATTERN)

    override fun loadUserByUsername(username: String): UserDetails {
        if (!usernamePattern.matcher(username).matches()) {
            throw UsernameFormatMismatchException()
        }

        val user = KtQueryChainWrapper(userMapper, UserPO::class.java)
            .eq(UserPO::username, username)
            .list()
            .firstOrNull()
            ?: throw UsernameNotFoundException(username)

        return DefaultUserDetails(user)
    }
}